/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.machineryrental.weblayer.validator;

import cz.muni.fi.pa165.machineryrental.dto.MachineDTO;
import cz.muni.fi.pa165.machineryrental.service.MachineService;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 *
 * @author jostri
 */
@Component
public class MachineValidator implements Validator {

    @Autowired
    private MachineService machineService;

    @Override
    public boolean supports(Class<?> type) {
        return MachineDTO.class.equals(type);
    }

    @Override
    public void validate(Object o, Errors errors) {
        System.out.println("Is validating");

        ValidationUtils.rejectIfEmpty(errors, "code", "machine.code.empty");
        ValidationUtils.rejectIfEmpty(errors, "brand", "machine.brand.empty");
        ValidationUtils.rejectIfEmpty(errors, "model", "machine.model.empty");
        ValidationUtils.rejectIfEmpty(errors, "yearOfProduction", "machine.yearOfProduction.empty");

        MachineDTO machine = (MachineDTO) o;

		// Machine id is bigger than 0? => Is edit formular, so we
        // dont check code - is read only
        if (machine.getId() == 0 && machine.getCode() != null) {
            if (!this.machineService.isCodeUnique(machine.getCode())) {
                errors.rejectValue("code", "machine.code.unique");
            }
        }

        if (machine.getYearOfProduction() != null) {
            if (machine.getYearOfProduction().compareTo(new Date()) > 0) {
                errors.rejectValue("yearOfProduction", "machine.yearOfProduction.dateafter");
            }
        }
    }

}
